<template>
  <div class="detail" ref="detailRef">
    <van-tabs 
      class="tab-control" 
      v-show="showTabControl" 
      v-model:active="activeName"
      @click-tab="tabClick">
      <template v-for="item of names">
        <van-tab :title="item" :name="item"></van-tab>
      </template>
    </van-tabs>
    <van-nav-bar
      title="房屋详情"
      left-text="旅途"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="main" v-if="mainPart" v-memo="[mainPart]">
      <swiper :swiper-data="mainPart?.topModule?.housePicture?.housePics"/>
    </div>
    <detail-info :top-infos="mainPart?.topModule"></detail-info>
    <detail-section name="房屋信息" :ref="getSectionRef" title="房屋信息" footer-text="查看全部设施">
      <div class="facility-inner">
        <template v-for="(item, index) of houseFacility?.houseFacilitys">
          <div class="item" v-if="houseFacility.facilitySort?.includes(index)">
            <div class="head">
              <img :src="item.icon" alt="">
              <div class="text">{{item.groupName}}</div>
            </div>
            <div class="list">
              <template v-for="item2 of item.facilitys.splice(0, 4)">
                <div class="list-item">
                  <img src="@/assets/img/detail/check.svg" alt="">
                  <span>{{item2.name}}</span>
                </div>
              </template>
            </div>
          </div>
        </template>
      </div>
    </detail-section>
    <detail-section name="位置周边" :ref="getSectionRef" title="位置周边" footer-text="查看更多周边信息">
      <!-- vue3使用ref -->
      <div class="baidu" ref="mapRef"></div>
    </detail-section>
    <detail-section name="测试区域" :ref="getSectionRef" title="测试区域" footer-text="测试区域">
      <div v-for="item in 100" :key="item">
        {{item}}
      </div>
    </detail-section>
    <div class="footer">
      尾部
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, reactive, computed, watch } from 'vue'
import { useRouter,useRoute } from 'vue-router'
import useScroll from "@/hooks/useScroll"
import {getDetailInfos} from "@/api"
import Swiper from "./components/swiper.vue"
import DetailInfo from "./components/detailInfo.vue"
import DetailSection from "./components/detailSection.vue"
const router = useRouter()

const onClickLeft = () => {
  router.back()
}

const mapRef = ref()
const longitude = computed(() => {
  return detailInfos.value.mainPart?.dynamicModule?.positionModule.longitude
})
const latitude = computed(() => {
  return detailInfos.value.mainPart?.dynamicModule?.positionModule.latitude
})
const detailInfos = ref({})
onMounted(async () => {
  const route = useRoute()
  const houseId = route.params.houseId
  const res = await getDetailInfos({houseId})
  detailInfos.value = res.data

  var map = new BMapGL.Map(mapRef.value);          // 创建地图实例 
  var point = new BMapGL.Point(longitude.value, latitude.value);  // 创建点坐标 
  map.centerAndZoom(point, 15);                 // 初始化地图，设置中心点坐标和地图级别
  const marker = new BMapGL.Marker(point)
  map.addOverlay(marker)
})

// 监听盒子滚动
const detailRef = ref()
const {scrollTop} = useScroll(detailRef)
const showTabControl = computed(() => {
  return scrollTop.value > 300
})

// 点击tabs跳转到相应的位置
const activeName = ref('房屋信息');
const sectionEls = ref({})
const getSectionRef = (value) => {
  if(!value) returnk
  const name = value.$el.getAttribute("name")
  sectionEls.value[name] = value.$el
}
const names = computed(() => {
  return Object.keys(sectionEls.value)
})
// 通过这两个变量优化滚动功能(滚动监听和点击滚动)
let isClick = false
let currentDistance = -1
const tabClick = (tabItem) => {
  const index = names.value.findIndex(name => name === tabItem.name)
  const key = Object.keys(sectionEls.value)[index]
  const el = sectionEls.value[key]
  let distance = el.offsetTop
  distance -= 44
  isClick = true
  currentDistance = distance
  detailRef.value.scrollTo({
    top: distance,
    behavior: "smooth"
  })
}

// 页面滚动，匹配相应的tab
watch(scrollTop, (newValue) => {
  if(newValue === currentDistance) {
    isClick = false
  }
  if(isClick) return
  const els = Object.values(sectionEls.value)
  const values = els.map(el => el.offsetTop)
  /** 
    理解清楚，这里有个小算法。
    如果某个区域的offsetTop(这里把offsetTo理解为某个范围的初始值)大于滚动的scrollTop，那么取这个区域的索引值(i)。
    但是呢，就屏幕的显示而言，我们应该取前面一个区域的索引值(i - 1)，因为offsetTop仍然逗留在前面一个区域。
    如果我们没法找到任何一个区域的offsetTop大于滚动的scrollTop，就说明滚动已经处于最后一个区域的范围内了，所以索引值找arr.length - 1
  */
  let index = values.length
  activeName.value = Object.keys(sectionEls.value)[index - 1]
  for(let i = 0; i < values.length; i++){
    if(values[i] > newValue + 44){
      if(i === 0) activeName.value = Object.keys(sectionEls.value)[0]
      activeName.value = Object.keys(sectionEls.value)[i -1]
      break
    }
  }
})

const mainPart = computed(() => {
  return detailInfos.value.mainPart
})
const houseFacility = computed(() => {
  return detailInfos.value.mainPart?.dynamicModule.facilityModule.houseFacility
})
</script>

<style lang='less' scoped>
.detail{
  height: calc(100vh - 50px);
  overflow-y: auto;
}
.tab-control{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}
.facility-inner{
  .item{
    padding: 10px 0;
    display: flex;
    .head{
      display: flex;
      flex: 4;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      img{
        width: 20px;
      }
    }
    .list{
      display: flex;
      flex-wrap: wrap;
      flex: 6;
      .list-item{
        width: 50%;
        img{
          width: 12px;
          margin-right: 5px;
        }
      }
    }
  }
}
.baidu{
  height: 300px;
}
.footer{
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: var(--primary-color);
  color: #000;
  font-weight: 600;
  font-size: 18px;
  text-align: center;
  height: 50px;
  line-height: 50px;
}
</style>